package org.wanho.txy.ems.service.impl;

import org.wanho.factory.ObjectFactory;
import org.wanho.txy.ems.constant.UserConstant;
import org.wanho.txy.ems.dao.UserDao;
import org.wanho.txy.ems.entity.User;
import org.wanho.txy.ems.exception.LoginErrorException;
import org.wanho.txy.ems.exception.UsernameExistsException;
import org.wanho.txy.ems.exception.UserModifyException;
import org.wanho.txy.ems.param.UserParam;
import org.wanho.txy.ems.service.UserService;
import org.wanho.txy.ems.util.MD5Util;

import java.util.Date;
import java.util.List;

/**
 * Author：汤小洋
 * Date：2023-05-10 15:35
 * Description：<描述>
 */
public class UserServiceImpl implements UserService {

    private UserDao userDao = (UserDao) ObjectFactory.getObject("userDao");

    @Override
    public User login(String username, String password) throws LoginErrorException {
        User user = userDao.selectUser(username, MD5Util.md5(password));
        if(user==null){
            throw new LoginErrorException("登录失败！");
        }
        return user;
    }

    @Override
    public void register(User user) throws UsernameExistsException {
        // 判断用户名是否被占用
        if(user.getUsername().equals("admin")){
            throw new UsernameExistsException("用户名已存在！");
        }

        user.setPassword(MD5Util.md5(user.getPassword()));
        user.setStatus(UserConstant.STATUS_DISABLE);
        user.setRegistDate(new Date());

        userDao.insert(user);
    }

    @Override
    public List<User> findByCondition(UserParam userParam, int pageNo, int pageSize) {
        List<User> users = userDao.selectByCondition(userParam,pageNo,pageSize);
        return users;
    }

    @Override
    public int selectCount(UserParam userParam) {
        return userDao.selectCount(userParam);
    }

    @Override
    public void modifyStatus(int id, int status) {
        userDao.updateStatus(id,status);
    }

    @Override
    public void removeById(int id) {
        userDao.deleteById(id);
    }

    @Override
    public User findById(int id) {
        return userDao.selectById(id);
    }

    @Override
    public void modify(User user) throws UserModifyException {
        /**
         * 判断用户名是否可用
         */
        User u = userDao.selectByUsername(user.getUsername());
        if(u != null && u.getId() != user.getId()){
            throw new UserModifyException("修改失败，用户名被占用！");
        }
        userDao.update(user);
    }

    @Override
    public void add(User user) throws UsernameExistsException {
        User u = userDao.selectByUsername(user.getUsername());
        if(u != null){
            throw new UsernameExistsException("用户名已存在！");
        }

        user.setPassword(MD5Util.md5(user.getPassword()));
        user.setStatus(UserConstant.STATUS_DISABLE);
        user.setRegistDate(new Date());

        userDao.insert(user);
    }
}
